using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Thunder.IrcClient
{
    /// <summary>
    /// DESCRIPTION 
    /// </summary>
    public class SortableObservableCollection<T> : ObservableCollection<T>
    {
        private bool sorting;

        public void Sort()
        {
            this.Sort(Comparer<T>.Default);
        }

        public void Sort(IComparer<T> comparer)
        {
            this.sorting = true;

            int i, j;
            for (i = 1; i < this.Count; i++)
            {
                T index = this[i];
                j = i;
                while ((j > 0) && (comparer.Compare(this[j - 1], index) == 1))
                {
                    this[j] = this[j - 1];
                    j = j - 1;
                }
                this[j] = index;
            }

            this.sorting = false;

            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (this.sorting == false)
            {
                base.OnCollectionChanged(e);
            }
        }
    }
}